/* 
 * Copyright (c) 2019, CENTRIN.CIYUN.LTD. All rights reserved.
 */
package com.cory.admin.sys.controller.portal;

import java.net.URLDecoder;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.cory.admin.sys.config.AdminConfig;
import com.cory.admin.sys.config.AdminConstants;
import com.cory.admin.sys.core.handle.SystemHandle.SystemSession;
import com.cory.admin.sys.domain.AdminPrincipal;
import com.cory.admin.sys.domain.entity.SysResource;
import com.cory.admin.sys.enums.EResourceType;
import com.cory.admin.sys.service.SysResourceService;
import com.cory.boot.base.BaseController;

/**
 * 功能嵌入页面
 * @author xiongcong
 * @date 2019-03-05
 */
@Controller
@RequestMapping("portal/iframe")
public class IframeController extends BaseController {
    @Autowired
    private SysResourceService sysResourceService;
    @Autowired
    private AdminConfig adminConfig;
    
    @GetMapping("")
    public String basics(HttpSession session, Model model, String code) {
        assertNotNull(code);
        return String.format("portal/%s/iframe", AdminConstants.MODEL);
    }
    
    @GetMapping("link")
    @SuppressWarnings("unchecked")
    public String link(HttpServletRequest request, Model model, HttpSession session, Integer menuId, String code, String param) {
        assertNotNull(code);
        SysResource resource = sysResourceService.getByCode(code);
        String url = resource != null ? resource.getUrl() : null;
        assertNotNull(url);
        
        if (resource.getReferId() != null) {
            List<SysResource> resources = (List<SysResource>)session.getAttribute(AdminConstants.SESSION_USER_RESOURCE);
            List<Integer> menuIds = resources.stream().filter(i -> i.getType() == EResourceType.MENU.key).map(i -> i.getId()).collect(Collectors.toList());
            if (!menuIds.contains(resource.getReferId())) {
                model.addAttribute("message", "您当前没有权限查看和处理该业务，如有需要请联系当前机构管理员！");
                return "common/message";
            }
        }
        
        if (url.startsWith("http://") || url.startsWith("https://")) {
            AdminPrincipal user = (AdminPrincipal)session.getAttribute(AdminConstants.SESSION_USER_INFO);
            if (url.indexOf("?") > 0) {
                url = url += "&token=" + user.getToken();
            } else {
                url = url += "?token=" + user.getToken();
            }
        }
        
        if (StringUtils.isNotBlank(param)) {
            try {
                param = URLDecoder.decode(param, "utf-8");
                url += (url.indexOf("?") > 0 ? "&" : "?") + param;
            } catch(Exception e) {}
        }
        
        System.out.println("--------跳转url-------" + url);
        return "redirect:" + url;
    }
    
    @GetMapping("index")
    @SuppressWarnings("unchecked")
    public String index(HttpSession session, Model model) {
        List<SysResource> resources = (List<SysResource>)session.getAttribute(AdminConstants.SESSION_USER_RESOURCE);
        SystemSession systemSession = (SystemSession)request.getSession().getAttribute(AdminConstants.SESSION_SYSTEM);
        
        if (StringUtils.isNotBlank(adminConfig.getIndexCode())) {
            SysResource home = resources.stream().filter(i -> adminConfig.getIndexCode().equals(i.getCode())).findFirst().orElse(null);
            
            if (home != null) {
                String indexCode = StringUtils.defaultIfBlank(systemSession.getIndexCode(), adminConfig.getIndexCode());
                return "redirect:" + String.format("/portal/iframe/link?code=%s", indexCode); 
            }
        }
        
        model.addAttribute("message", String.format("欢迎访问%s·%s", adminConfig.getAppName(), StringUtils.defaultIfBlank(systemSession.getSysName(), adminConfig.getSysName())));
        return "boot/message";
    }
}
